package com.baidu.iit.pvm.runtime;

import com.baidu.iit.pvm.PvmEventConstacts;
import com.baidu.iit.pvm.process.ActivityImpl;
import com.baidu.iit.pvm.process.ScopeImpl;
import com.baidu.iit.pvm.process.TransitionImpl;

/**
 * 当路径开始流转时触发的动作
 *
 * @ThreadSafe
 * Created by 卫立 on 2014/4/7.
 */
public class AtomicOperationTransitionNotifyListenerStart extends AbstractEventAtomicOperation {

    @Override
    protected ScopeImpl getScope(InterpretableExecution execution) {
        return (ScopeImpl) execution.getActivity();
    }

    @Override
    protected String getEventName() {
        return PvmEventConstacts.EVENTNAME_START;
    }



    @Override
    protected void eventNotificationsCompleted(InterpretableExecution execution) {
        TransitionImpl transition = execution.getTransition();
        ActivityImpl destination = null;
        if(transition == null) {
            destination = (ActivityImpl) execution.getActivity();
        } else {
            destination = transition.getDestination();
        }
        ActivityImpl activity = (ActivityImpl) execution.getActivity();


        if (activity!=destination) {
            ActivityImpl nextScope = AtomicOperationTransitionNotifyListenerTake.findNextScope(activity, destination);
            execution.setActivity(nextScope);
            execution.performOperation(TRANSITION_CREATE_SCOPE);
        } else {
            //这里特殊处理，可能会发生死循环，需要在流程定义中杜绝
            //出现这种情况是为了实现循环功能
            execution.setTransition(null);
            execution.setActivity(destination);
            execution.performOperation(ACTIVITY_EXECUTE);
        }
    }
}
